import React from "react";
import { RouteRawState } from "../types";
import { useSelector, useDispatch } from "react-redux";
import { Navigate } from "react-router-dom";

interface PorpsType {
  route: RouteRawState;
}

const Index: React.FC<PorpsType> = ({ route }) => {
  const isLogin = useSelector((state: any) => state.user.isLogin);
  const role = useSelector((state: any) => state.user.userInfo.role);
  // 1. 已登录
  if (isLogin) {
    if (route.path === "/login") {
      // 1-1. 访问登录页面  => 拦截去首页
      return <Navigate to="/"></Navigate>;
    } else {
      // 没有权限要求  直接访问
      if (!route.meta.roles) return route.element;
      else {
        // 1-2. 访问非登录页面 => 验证权限 => 通过正常访问
        if (route.meta.roles.includes(role)) {
          return route.element;
        } else {
          //  =>  403 没有权限访问
          return <Navigate to="/403"></Navigate>
        }
      }
    }
  }

  // 2. 未登录
  else {
    if (route.path === "/login") {
      // 2-1 访问登录页面  => 正常访问
      return route.element;
    } else {
      // 2-2 访问非登录页面 => 拦截去登录
      return <Navigate to="/login"></Navigate>;
    }
  }
};

export default Index;
